import React, { useState, useEffect, useCallback } from 'react';
import { Button } from './ui/button';
import { Slider } from './ui/slider';
import { Play, Pause, RotateCcw, Settings } from 'lucide-react';

interface PomodoroTimerProps {
  workMinutes?: number;
  onWorkComplete: () => void;
}

const PomodoroTimer: React.FC<PomodoroTimerProps> = ({
  workMinutes = 5,
  onWorkComplete
}) => {
  const [customMinutes, setCustomMinutes] = useState(workMinutes);
  const [timeLeft, setTimeLeft] = useState(workMinutes); // 直接使用秒数
  const [isRunning, setIsRunning] = useState(false);
  const [isWorkSession, setIsWorkSession] = useState(true);
  const [showSettings, setShowSettings] = useState(false);
  
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };
  
  const handleStart = () => {
    setIsRunning(true);
  };
  
  const handlePause = () => {
    setIsRunning(false);
  };
  
  const handleReset = () => {
    setIsRunning(false);
    setTimeLeft(customMinutes);
    setIsWorkSession(true);
  };

  const handleTimeChange = (value: number[]) => {
    if (!isRunning) {
      const newSeconds = value[0];
      setCustomMinutes(newSeconds);
      setTimeLeft(newSeconds);
    }
  };
  
  const handleComplete = useCallback(() => {
    setIsRunning(false);
    if (isWorkSession) {
      onWorkComplete();
    }
  }, [isWorkSession, onWorkComplete]);
  
  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (isRunning && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            handleComplete();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isRunning, timeLeft, handleComplete]);
  
  const progressPercentage = ((customMinutes - timeLeft) / customMinutes) * 100;
  
  return (
    <div className="card-healing text-center max-w-lg mx-auto">
      {/* 时间设置面板 */}
      {showSettings && (
        <div className="settings-panel mb-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold bg-gradient-to-r from-primary to-mint bg-clip-text text-transparent">
              专注时长设置
            </h3>
            <span className="text-2xl font-bold bg-gradient-to-r from-tomato to-mint bg-clip-text text-transparent">
              {customMinutes}秒
            </span>
          </div>
          <div className="slider-healing">
            <Slider
              value={[customMinutes]}
              onValueChange={handleTimeChange}
              min={5}
              max={300}
              step={5}
              disabled={isRunning}
              className="mb-2"
            />
            <div className="flex justify-between text-xs text-muted-foreground">
              <span>5秒</span>
              <span>5分钟</span>
            </div>
          </div>
        </div>
      )}

      <div className="mb-8">
        <div className="flex items-center justify-center gap-2 mb-4">
          <h1 className="text-6xl font-bold bg-gradient-to-br from-tomato via-primary to-mint bg-clip-text text-transparent">
            {formatTime(timeLeft)}
          </h1>
          <Button
            onClick={() => setShowSettings(!showSettings)}
            variant="ghost"
            size="sm"
            className="ml-2 opacity-60 hover:opacity-100 transition-opacity"
            disabled={isRunning}
          >
            <Settings className="h-4 w-4" />
          </Button>
        </div>
        <p className="text-lg bg-gradient-to-r from-muted-foreground to-primary/80 bg-clip-text text-transparent">
          {isWorkSession ? '专注工作时间' : '休息时间'}
        </p>
      </div>
      
      {/* 进度条 */}
      <div className="mb-8">
        <div className="relative w-full bg-gradient-to-r from-muted/50 to-muted/30 rounded-full h-4 overflow-hidden backdrop-blur-sm">
          <div 
            className="h-full bg-gradient-to-r from-tomato via-primary to-mint transition-all duration-500 ease-out shadow-glow"
            style={{ width: `${progressPercentage}%` }}
          />
          <div className="absolute inset-0 bg-gradient-to-r from-white/20 to-transparent rounded-full pointer-events-none" />
        </div>
        <p className="text-sm bg-gradient-to-r from-muted-foreground to-primary/70 bg-clip-text text-transparent mt-3 font-medium">
          {Math.round(progressPercentage)}% 完成 · 还有 {timeLeft}秒
        </p>
      </div>
      
      {/* 控制按钮 */}
      <div className="flex justify-center gap-4">
        {!isRunning ? (
          <Button
            onClick={handleStart}
            className="btn-healing btn-primary"
            size="lg"
          >
            <Play className="mr-2 h-5 w-5" />
            {timeLeft === customMinutes * 60 ? '开始番茄' : '开始'}
          </Button>
        ) : (
          <Button
            onClick={handlePause}
            className="btn-healing btn-tomato"
            size="lg"
          >
            <Pause className="mr-2 h-5 w-5" />
            暂停
          </Button>
        )}
        
        <Button
          onClick={handleReset}
          variant="outline"
          size="lg"
          className="rounded-full bg-gradient-to-r from-background/80 to-muted/40 backdrop-blur-sm border-border/30 hover:border-primary/30"
        >
          <RotateCcw className="mr-2 h-4 w-4" />
          重置
        </Button>
      </div>
      
      <div className="mt-8 text-center">
        <p className="text-sm bg-gradient-to-r from-muted-foreground via-primary/60 to-mint bg-clip-text text-transparent font-medium">
          完成后我们一起做些健康的运动吧！ 🍅✨
        </p>
      </div>
    </div>
  );
};

export default PomodoroTimer;